package com.southminority.ethnic.service.course.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.southminority.ethnic.pojo.CourseEvaluation;
import com.southminority.ethnic.pojo.Course;
import com.southminority.ethnic.mapper.course.CourseEvaluationMapper;
import com.southminority.ethnic.mapper.course.CourseMapper;
import com.southminority.ethnic.service.course.CourseEvaluationService;
import com.southminority.ethnic.service.course.CourseService;
import com.southminority.ethnic.controller.coures.vo.CourseEvaluationSummaryVo;
import com.southminority.ethnic.controller.coures.vo.CourseEvaluationVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author ASHTR
* @description 针对表【course_evaluation(课程评价表)】的数据库操作Service实现
* @createDate 2025-01-20 10:00:00
*/
@Slf4j
@Service
public class CourseEvaluationServiceImpl extends ServiceImpl<CourseEvaluationMapper, CourseEvaluation> implements CourseEvaluationService {

    @Autowired
    private CourseService courseService;

    @Override
    @Transactional
    public Boolean InputList(List<CourseEvaluation> list) {


        return null;
    }

    @Override
    public List<CourseEvaluation> getEvaluationsByCourseId(Long courseId) {
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseEvaluation::getCourseId, courseId)
                .orderByDesc(CourseEvaluation::getCreateTime);
        return this.list(wrapper);
    }

    @Override
    public List<CourseEvaluation> getEvaluationsByUserId(Long userId) {
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseEvaluation::getUserId, userId)
                .orderByDesc(CourseEvaluation::getCreateTime);
        return this.list(wrapper);
    }

    @Override
    public Double getAverageRating(Long courseId) {
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseEvaluation::getCourseId, courseId)
                .select(CourseEvaluation::getRating);
        
        List<CourseEvaluation> evaluations = this.list(wrapper);
        if (evaluations.isEmpty()) {
            return 0.0;
        }
        
        double totalRating = evaluations.stream()
                .mapToInt(CourseEvaluation::getRating)
                .sum();
        
        return Math.round((totalRating / evaluations.size()) * 10.0) / 10.0; // 保留一位小数
    }

    @Override
    public CourseEvaluationSummaryVo getEvaluationSummary(Long courseId, Long userId) {
        CourseEvaluationSummaryVo summary = new CourseEvaluationSummaryVo();
        summary.setCourseId(courseId);
        
        // 获取所有评价
        List<CourseEvaluation> evaluations = getEvaluationsByCourseId(courseId);
        
        // 计算平均评分
        Double averageRating = getAverageRating(courseId);
        summary.setAverageRating(averageRating);
        
        // 设置评价总数
        summary.setTotalCount(evaluations.size());
        
        // 转换为VO
        List<CourseEvaluationVo> evaluationVos = evaluations.stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());
        summary.setEvaluations(evaluationVos);
        
        // 检查当前用户是否已评价
        Boolean hasUserEvaluated = hasUserEvaluated(courseId, userId);
        summary.setHasUserEvaluated(hasUserEvaluated);
        
        // 如果用户已评价，获取用户评价
        if (hasUserEvaluated) {
            CourseEvaluation userEvaluation = getUserEvaluation(courseId, userId);
            summary.setUserEvaluation(convertToVo(userEvaluation));
        }
        
        return summary;
    }

    @Override
    @Transactional
    public synchronized CourseEvaluation addOrUpdateEvaluation(Long courseId, Long userId, String userName, Integer rating, String content) {
        // 检查是否已存在评价
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseEvaluation::getCourseId, courseId)
                .eq(CourseEvaluation::getUserId, userId);
        CourseEvaluation existingEvaluation = baseMapper.selectOne( wrapper);
        
        if (existingEvaluation != null) {
            // 更新现有评价
            existingEvaluation.setRating(rating);
            existingEvaluation.setContent(content);
            existingEvaluation.setUserName(userName);
            this.updateById(existingEvaluation);
            log.info("更新课程评价，课程ID: {}, 用户ID: {}", courseId, userId);
        } else {
            // 创建新评价
            CourseEvaluation newEvaluation = new CourseEvaluation();
            newEvaluation.setCourseId(courseId);
            newEvaluation.setUserId(userId);
            newEvaluation.setUserName(userName);
            newEvaluation.setRating(rating);
            newEvaluation.setContent(content);
            this.save(newEvaluation);
            log.info("添加课程评价，课程ID: {}, 用户ID: {}", courseId, userId);
            existingEvaluation = newEvaluation;
        }
        
        // 更新课程表中的评分
        updateCourseRating(courseId);
        
        return existingEvaluation;
    }

    @Override
    public Boolean hasUserEvaluated(Long courseId, Long userId) {
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseEvaluation::getCourseId, courseId)
                .eq(CourseEvaluation::getUserId, userId);
        return this.count(wrapper) > 0;
    }

    @Override
    public CourseEvaluation getUserEvaluation(Long courseId, Long userId) {
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CourseEvaluation::getCourseId, courseId)
                .eq(CourseEvaluation::getUserId, userId);
        log.info("获取用户评价，课程ID: {}, 用户ID: {}", courseId, userId);
        CourseEvaluation evaluation = this.getOne(wrapper);
        if (evaluation == null){
            throw new RuntimeException("用户评价不存在");
        }
        return evaluation;
    }

    /**
     * 将实体转换为VO
     */
    private CourseEvaluationVo convertToVo(CourseEvaluation evaluation) {
        if (evaluation == null) {
            return null;
        }
        CourseEvaluationVo vo = new CourseEvaluationVo();
        BeanUtils.copyProperties(evaluation, vo);
        return vo;
    }

    @Override
    @Transactional
    public Boolean deleteUserEvaluation(Long courseId, Long userId) {
        try {
            // 检查是否存在评价
            CourseEvaluation evaluation = getUserEvaluation(courseId, userId);
            if (evaluation == null) {
                log.warn("用户评价不存在，课程ID: {}, 用户ID: {}", courseId, userId);
                return false;
            }
            
            // 删除评价
            boolean deleted = this.removeById(evaluation.getId());
            if (deleted) {
                log.info("删除课程评价成功，课程ID: {}, 用户ID: {}", courseId, userId);
                // 更新课程表中的评分
                updateCourseRating(courseId);
                return true;
            } else {
                log.error("删除课程评价失败，课程ID: {}, 用户ID: {}", courseId, userId);
                return false;
            }
        } catch (Exception e) {
            log.error("删除课程评价时发生异常，课程ID: {}, 用户ID: {}", courseId, userId, e);
            return false;
        }
    }

    /**
     * 更新课程表中的评分
     * @param courseId 课程ID
     */
    private void updateCourseRating(Long courseId) {
        try {
            // 计算新的平均评分
            Double newAverageRating = getAverageRating(courseId);
            
            // 更新课程表中的评分
            Course course = courseService.getById(courseId);
            if (course != null) {
                course.setStar(newAverageRating);
                boolean updated = courseService.updateById(course);
                if (updated) {
                    log.info("课程评分更新成功，课程ID: {}, 新评分: {}", courseId, newAverageRating);
                } else {
                    log.error("课程评分更新失败，课程ID: {}", courseId);
                }
            } else {
                log.error("课程不存在，无法更新评分，课程ID: {}", courseId);
            }
        } catch (Exception e) {
            log.error("更新课程评分时发生异常，课程ID: {}", courseId, e);
        }
    }

    @Override
    public Page<CourseEvaluation> getEvaluationPageWithKeyword(Page<CourseEvaluation> page, String keyword) {
        LambdaQueryWrapper<CourseEvaluation> wrapper = new LambdaQueryWrapper<>();
        
        // 如果有关键词，进行模糊查询
        if (StringUtils.hasText(keyword)) {
            wrapper.like(CourseEvaluation::getUserName, keyword)
                    .or()
                    .like(CourseEvaluation::getContent, keyword);
        }
        
        // 按创建时间倒序排列
        wrapper.orderByDesc(CourseEvaluation::getCreateTime);
        
        return this.page(page, wrapper);
    }
} 